package com.jelly.io.collect;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.TreeSet;

public class TextFile extends ArrayList<String>{

	private static final long serialVersionUID = 4020482963196197254L;
	
	//Read a file as a single string
	public static String read(String fileName) throws IOException{
		StringBuffer sb = new StringBuffer();
		try {
			BufferedReader in = new BufferedReader(new FileReader(new File(fileName).getAbsolutePath()));
			String s;
			while(null!=(s=in.readLine())){
				sb.append(s);
				sb.append("\n");
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}
	//write a single in one method call
	public static void write(String fileName,String text) throws FileNotFoundException{
		PrintWriter out = new PrintWriter(new File(fileName).getAbsolutePath());
		out.print(text);
		out.flush();
		out.close();
	}
	/**
	 * Read a file,split by any regular expression
	 * @param fileName
	 * @param splitter
	 * @throws IOException 
	 */
	public TextFile(String fileName,String splitter) throws IOException{
		super(Arrays.asList(read(fileName).split(splitter)));
		//Regular expression split() often leave an empty
		//String at the first position:
		if(get(0).equals(""))remove(0);
	}
	//Normally read by lines
	public TextFile(String fileName) throws IOException{
		this(fileName,"\n");
	}
	
	public void write(String fileName){
		PrintWriter out=null;
		try {
			out = new PrintWriter(new File(fileName).getAbsolutePath());
			for (String item:this) {
				out.println(item);
			}
			out.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) throws IOException {
		String file =read("src\\com\\jelly\\io\\collect\\TextFile.java");
		write("text.txt", file);
		TextFile text = new TextFile("text.txt");
		text.write("test2.txt");
		TreeSet<String> words = new TreeSet<String>(new TextFile("src\\com\\jelly\\io\\collect\\TextFile.java","\\w+"));
		System.out.println(words.headSet("a"));
	}
}
